// pages/run/index.js
import timer from "../../utils/lebu-timer";
import lebu from "../../utils/lebu-core";
import lableAll from "../../utils/mapLable";

const curTimes = 1;  //初始值为1，跑步的初始次数
const app = getApp();
const getSecretMsg = app.globalData.secretMsg;  //获取秘闻
var getSvInfo = app.globalData.serverInfo;  //获取信息
const lable = lableAll.getAllLable();

var scoreNumber = 7; //进过点的数量要求  7 6
var scoreClearnNumber = 8; //步骤条再第几个进行清空  8 7
var scoreLastScoll = 6 //最后一圈监听器，是否重置步骤条的条件  6 5
var uuidAll = app.globalData.uuidAll;
var pointIndex = 1; //打卡出发点初始值
var allPointInfo4Finish = [];
var checkIfPokPoint = 0;  //判断是否打卡、
var runStartTime = ""; //点击跑步，记录起跑时间

var ifRunStart = false; //跑步状态阀门，解决退出改变motion_status状态,4.12版本
const fixedUuids = [
    "01122334-4556-6778-899a-abbccddeeff0",
    "02122334-4556-6778-899a-abbccddeeff0",
    "03122334-4556-6778-899a-abbccddeeff0",
    "04122334-4556-6778-899a-abbccddeeff0",
    "05122334-4556-6778-899a-abbccddeeff0",
    "06122334-4556-6778-899a-abbccddeeff0"
];

Page({

  /**
   * 页面的初始数据
   */
  data: {
    basicsList: [{
      icon: 'usefullfill',
      name: '开始'
    }, {
      icon: 'radioboxfill',
      name: '点1'
    }, {
      icon: 'roundclosefill',
      name: '点2'
    }
    , {
      icon: 'roundcheckfill',
      name: '点3'
    },
     {
      icon: 'usefullfill',
      name: '点4'
    },
     {
      icon: 'radioboxfill',
      name: '点5'
    }, {
      icon: 'roundclosefill',
      name: '点6'
    }, {
      icon: 'roundcheckfill',
      name: '点7'
    },

  ],
    basics: 0,
    numList: [{
      name: '我的',
      pointStatus: '起点'
    }, {
      name: '',
      pointStatus: ''
    }, {
      name: '',
      pointStatus: ''
    },{
      name: '',
      pointStatus: ''
    },,{
      name: '',
      pointStatus: ''
    },{
      name: '',
      pointStatus: ''
    },{
      name: '',
      pointStatus: ''
    },{
      name: '',
      pointStatus: ''
    },
  ],
    num: 0,
    scroll: 0,

    _msg: '你好',
    screenHeight: 0,
    polyline: [{
      points: [],
      color: "#07c160",
      width: 2
    }],
    latitude: 0,
    longitude: 0,
    altitude_data: [],
    time_data: "00:00:00",
    kcal_data: "0.00",
    speed_data: "0'00\"",
    distance_data: "0.00",
    // step_data:"0",
    motion_status: 0,
    time_id: 0,
    points_time: parseInt(Date.now() / 1000),
    km_speed_data: [],
    km_distance_data: 0,
    runType: 0,
    sportHaoshi1: "",
    sportDistant: "",
    sportStart:"",
    sportEnd:"",
    scale:14.8,

    markers: lable
    ,


  },
  tabSelect(e) {
    this.setData({
      runType: e.currentTarget.dataset.id,
    })
  },

  //初始化numList,当完成一组后，清空点位信息，为下一轮做准备
  initNumList(){
    var that = this;
    var i = 1;
    for(; i < that.data.numList.length; i++){
      that.data.numList[i].name = ''
      that.data.numList[i].pointStatus = ''
    }
  },

  /*
    返回插件说明:
    1、本项目没有使用wx.navigateBack()返回，如果使用该返回，需要搭配使用wx.removeStorageSync('showBackModal')，不然会被拦截
    2、使用wx.navigateTo 不会被拦截，本项目使用
  */
  onBeforeBack: function () {
    // 只要页面存在这个方法，并返回return wx.showModal就会监听拦截用户返回动作
    return wx.showModal({
      title: '提示',
      content: '信息尚未保存，确定要返回吗？',
      confirmStay: !1 //结合content意思，点击确定按钮后，是否留在原来页面，confirmStay默认false
    })
  },

      /**
     * 生命周期函数--监听页面加载
     */
  onHide:function(){
      
      this.closeBluetoothAdapter();
     
  },

  /**P
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;

    //初始化点位索引值
    pointIndex = 1;
    checkIfPokPoint = 0;
    runStartTime = "";
    ifRunStart = false;
    //暂时不考虑数据保存问题，只要退出，只能重新跑 
    let id = timer.getTodayHour();
    wx.removeStorageSync('pointItem-' + id); 

    that.initRun();
    if (that.data.runType == 0) {
      let sub_obj = "polyline[" + 0 + "].points"
      wx.onLocationChange((result) => {
        // let ex_steps = result.steps;//获取定位步数
        // lebu.setSteps(ex_steps);
        let points = that.data.polyline[0].points;
        //检测距离
        if (that.data.polyline[0].points.length == 0 || that.checkDistance(result.latitude, result.longitude, parseInt(Date.now() / 1000))) {
          points.push({
            longitude: result.longitude,
            latitude: result.latitude
          });
          that.setData({
            [sub_obj]: points,
            longitude: result.longitude,
            latitude: result.latitude,
          });
        }
      })
    }
    
  },
    // 停止设备扫描
    stopBluetoothDevicesDiscovery() {
      wx.stopBluetoothDevicesDiscovery()
      // wx.hideLoading();
      wx.hideLoading({
        complete: (res) => {},
      })
  },

  //关闭模块
  closeBluetoothAdapter() {
    console.log("关闭蓝牙扫描")
    this.stopBluetoothDevicesDiscovery()
    wx.closeBluetoothAdapter()
    this._discoveryStarted = false
  },

  //蓝牙
  openBluetoothAdapter(){
    wx.openBluetoothAdapter({
      success: (res) => {
        //开始扫描，并转换显示状态为停止扫描
        this.setData({
          motion_status:3
        })
        console.log('打开蓝牙适配器成功', res)
        this.startBluetoothDevicesDiscovery()
      },
      fail: (res) => {
        console.log(res)
        if (res.errCode === 10001) {
          wx.showToast({
            title: '请打开蓝牙!',
          })
        }
      }
    })
    
  },
    //蓝牙模块
startBluetoothDevicesDiscovery() {
    if (this._discoveryStarted) {
      return
    }
    this._discoveryStarted = true
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      success: (res) => {
        console.log('绑定开始蓝牙设备搜索成功', res)
        // this.onBluetoothDeviceFound()
        this.startIbeacon()
      },
    })
  },


  //停止扫描
  stopBluetoothDevicesDiscovery() {
    var that = this;
    
    if(!ifRunStart){
      that.setData({
        motion_status:0
      })
    }else{
      that.setData({
        motion_status:1
      })
    }

    wx.stopBluetoothDevicesDiscovery({
      success(res){
        console.log(res)
        wx.closeBluetoothAdapter()
        that._discoveryStarted = false
        wx.hideLoading({
          success: (res) => {},
        })
      },
      fail(err){
        console.log(err)
      }
    })

  },

//   onBluetoothDeviceFound() {
//     let that = this;
//     console.log(runStartTime);
//     wx.showLoading({
//         title: '搜索范围设备....',
//         // mask: true  // 不允许用户点击界面
//     });

//     wx.onBluetoothDeviceFound((res) => {


//         res.devices.forEach(device => {
//             if (!device.name && !device.localName) {
//                 return;
//             }

//             console.log(device);

//             // 使用固定的 UUID 数组进行比对
//             const fixedUuids = [
//                 "01122334-4556-6778-899a-abbccddeeff0",
//                 "02122334-4556-6778-899a-abbccddeeff0",
//                 "03122334-4556-6778-899a-abbccddeeff0",
//                 "04122334-4556-6778-899a-abbccddeeff0",
//                 "05122334-4556-6778-899a-abbccddeeff0",
//                 "06122334-4556-6778-899a-abbccddeeff0"
//             ];

//             // 检查扫描到的设备 UUID 是否在固定数组中
//             const foundUuid = fixedUuids.find(uuid => device.localName === uuid || device.name === uuid);

//             if (foundUuid) {
//                 // 找到匹配的 UUID
//                 wx.vibrateShort({
//                     complete: (res) => {},
//                 });

//                 wx.hideLoading({
//                     success: (res) => {},
//                 });

//                 // 获取当前缓存打卡信息
//                 let id = timer.getTodayHour();
//                 var currentPonit = wx.getStorageSync('pointItem-' + id);

//                 // 检查当前缓存中是否已经打卡过该点
//                 for (var i = 0; i < currentPonit.length; i++) {
//                     if (currentPonit[i].uuid === foundUuid) {
//                         checkIfPokPoint++;
//                     }
//                 }

//                 if (checkIfPokPoint > 0) {
//                     // 提示用户已打卡
//                     checkIfPokPoint = 0;
//                     wx.showToast({
//                         title: '此处已打卡!',
//                     });
//                 } else {
//                     // 执行打卡逻辑
//                     checkIfPokPoint = 0;

//                     // 获取当前时间
//                     var curTime = timer.getTodayTime();

//                     // 计算耗时时长
//                     var getHaoshi = timer.getTmC(runStartTime, curTime);

//                     // 获取匹配的 UUID 对应的信息
//                     const fetchDevInfo = uuidAll.find(item => item.uuid === foundUuid);

//                     // 调用打卡信息设置方法
//                     that.setCurrentIbeaconInfo(fetchDevInfo, curTime, getHaoshi);
//                 }
//             }
//         });
//     });
// },



  startIbeacon(){
    var that = this;
    var devices = [];
    var uuidArray = ["01122334-4556-6778-899a-abbccddeeff0",
    "02122334-4556-6778-899a-abbccddeeff0","03122334-4556-6778-899a-abbccddeeff0","04122334-4556-6778-899a-abbccddeeff0","05122334-4556-6778-899a-abbccddeeff0","06122334-4556-6778-899a-abbccddeeff0",]

    console.log(uuidArray)
    wx.showLoading({
      title: '搜索范围设备....',
    })

    // 开始扫描
    wx.startBeaconDiscovery({
        uuids: uuidArray,
        success: function () {
            console.log("开始扫描设备....");
        // 监听iBeacon信号
            wx.onBeaconUpdate(function (res) {
              console.log('startIbeacon():'+res)               
                const beaconUuid = res.beacons[0].uuid;
                console.log('beaconUuid:'+beaconUuid) 
                // 请注意，官方文档此处又有BUG，是res.beacons，不是beacons。
                if (res && res.beacons[0] && res.beacons[0].length > 0) {
                    devices = res.beacons[0];
                    // 此处最好检测rssi是否等于0，等于0的话信号强度等信息不准确。我是5秒内重复扫描排重。
                    //获取当前缓存打卡信息
                    let id = timer.getTodayHour();
                    var currentPonit = wx.getStorageSync('pointItem-' + id)
                    //检查是否有uuidarray数字
                    for(var i = 0; i < uuidAll.length; i++){
                      for(var l = 0; l < devices.length; l++){
                        if(uuidAll[i].uuid === devices[l].uuid && devices[l].major === uuidAll[i].major ){
                          //停止扫描
                          // that.timeout();
                          var currentCheckDevInfo = devices[l];
                          var fetchDevInfo = uuidAll[i]
                          //关闭扫描
                          wx.stopBeaconDiscovery({
                            success: function () {

                            //查询到增加震动
                            wx.vibrateShort({
                              complete: (res) => {},
                            })

                            //设定检测状态
                             wx.hideLoading({
                              success: (res) => {},
                            })
  
                            //判断当前缓存打卡uuid是否等于当前检录设备打卡uuid
                            for(var i = 0; i < currentPonit.length; i++){
                              if(currentPonit[i].uuid === currentCheckDevInfo.uuid){
                                 checkIfPokPoint++;
                              }
                            }

                            //如果checkIfPokPoint  大于0 ，说明缓存中存在已经打卡的点
                            //需要提示用户不能再在打卡
                            
                            if(checkIfPokPoint > 0){
                               checkIfPokPoint = 0; 
                                wx.showToast({
                                  title: '此处已打卡!',
                                })
                              }else{
                                checkIfPokPoint = 0;
                                //缓存并更新打卡点信息,并获取当前时间
                                var curTime = timer.getTodayTime();
                                //根据起跑时间和打卡时间，计算出耗时时长
                                var getHaoshi = timer.getTmC(runStartTime, curTime)
                                that.setCurrentIbeaconInfo(fetchDevInfo, curTime,getHaoshi)
                              }
                            }
                          });

                        }
                      }
                    }
                }
            });
        },
        fail:function(err){
          //失败的时候也要清除打卡是否重复索引值
          checkIfPokPoint = 0;
          wx.hideLoading({
            success: (res) => {},
          })
         
          if (err.errCode === 11001) {
            wx.showToast({
              title: '请打开蓝牙!',
            })
          }
          if(err.errCode === 11003){
            wx.showToast({
              title: '10秒后再尝试!',
            })
            
          }

          that.timeout();
        }
    });
    
  },

  //停止扫描
  timeout(){
    wx.stopBeaconDiscovery({
      success: function () {
          console.log("停止设备扫描！");
      }
  });
  },

  //进行位置信息设置
  setCurrentIbeaconInfo(itemPoint, curTime, getHaoshi){
    var that = this;
  
    //numList从第二个开始，数组也是从1开始
    console.log(pointIndex)
    console.log(that.data.scroll)

    let id = timer.getTodayHour();
    //这是一圈终点打卡，记录完成次数（以年为单位）{该模块单独提出来，减少模块分支判断复杂度}
    if(pointIndex === scoreNumber && that.data.scroll === scoreLastScoll ){
      //完成一组，记录完成次数（以年为单位）
  
      var getLastTimes = wx.getStorageSync(getSecretMsg +  "2025");
      if(!getLastTimes > 0){
        
        wx.setStorageSync(getSecretMsg + "2025", curTimes)  //如果第一次，设定为1
      }else{
        
        getLastTimes += 1;
        wx.setStorageSync(getSecretMsg + "2025", getLastTimes)
      }

      //完成一组，执行打卡记录状态修改
      var getStructIfPonit = wx.getStorageSync('pointContent');
      getStructIfPonit[0].nyrBoolean = true;
      wx.setStorageSync('pointContent', getStructIfPonit)
      
    }
    
    //这是一圈终点打卡，需要提醒用户，并记录最近一次和清除数据操作
    if(pointIndex === scoreNumber && that.data.scroll === scoreLastScoll ){
      wx.showModal({
        title: '打卡提示',
        content: '已经完成一圈记录，是否提交',
        showCancel:false,
        cancelText: '舍弃',
        confirmText: '提交',
        success(res) {
          if (res.confirm) {
            //重置点位信息以及点的name
            pointIndex = 1;
            that.initNumList();

            //完成一组后，记录为最近打卡数据
            let finishLen = allPointInfo4Finish.length - 1;
            let ids = parseInt(Date.now() / 1000)
            
            wx.setStorageSync('recentPointRec-' + ids, JSON.stringify({
               sportHaoshi:    allPointInfo4Finish[finishLen].pointHaoshi,
               sportDistant:   (finishLen + 1) + "次",
               sportStart:     allPointInfo4Finish[finishLen].pointRunStart,
               sportEnd:       allPointInfo4Finish[finishLen].pointTime,
               runType:        that.data.runType
            }));

            
            //刷新打卡界面UI, 并初始化跑步状态
            that.setData({
              scroll: that.data.scroll === scoreClearnNumber ? 0 : that.data.scroll + 1,
              ['numList']: that.data.numList,
            })

            //完成一组，清除最后一次打卡点缓存
            // wx.removeStorageSync('pointItem-' + id);

            //完成一组，清除全局数组
            allPointInfo4Finish = [];

            //完成一组 ，清除起跑时间
            runStartTime = "";

            //完成一组，充值起跑计时器
            timer.end();
            timer.reset();

            //完成一组后，跳转到记录页面
            wx.redirectTo({
              url: './statement?id=' + ids,
            })
          } 
        }
      })
    }

    //存储、设置每个打卡点的数据信息
    if(pointIndex <= scoreNumber && that.data.scroll <= scoreClearnNumber ){
      
      //缓存当前打卡位置信息并删除上一个缓存（缓存有时间限制，24个小时后自动清除）
      //下次访问，提供放弃、继续两种模式


      //给当前打卡节点数据增加时间赋值
      itemPoint.pointTime = curTime;
      //存储起跑的时间，给每个打卡点
      itemPoint.pointRunStart = runStartTime;

      //存储每个打卡点，用时、耗时时长
      itemPoint.pointHaoshi = getHaoshi;
      
      //跑步数据存放为数组对象，并丢到缓存中
      allPointInfo4Finish.push(itemPoint);
      
      //将小时修改为年月日形式，不然上面代码对于判断是否存在，超出当前小时，会一直不存在，可以一直打卡
      let id = timer.getTodayHour();
      // wx.removeStorageSync('pointItem' + id);
      wx.setStorageSync('pointItem-' + id, allPointInfo4Finish)

      //打印当前缓存
      var str = wx.getStorageSync('pointItem-' + id)
      console.log(str)
      //显示打卡成功标志
      wx.showToast({
        title: '打卡成功',
        icon: 'success',
        duration: 2000
      })
     
      that.setData({
        ['numList[' + pointIndex + '].name']:itemPoint.lable,
        ['numList[' + pointIndex + '].pointStatus']:itemPoint.pointStatus,
        // that.data.scroll === X 显示完成数量
        scroll: that.data.scroll === scoreClearnNumber ? 0 : that.data.scroll + 1
      })
     
      pointIndex++;
    
    }
// 如果完成所有打卡点，发送数据到后端
    if (pointIndex > scoreNumber && that.data.scroll === scoreLastScoll) {
        that.sendClockDataToBackend();
    }
  },


  sendClockDataToBackend() {
    var that = this;

    // 获取缓存数据
    let id = timer.getTodayHour();
    let allPoints = wx.getStorageSync('pointItem-' + id) || [];
    let openid = wx.getStorageSync('openid'); // 假设 openid 已经缓存
    let userId = wx.getStorageSync('userId'); // 假设 userId 已经缓存

    // 构造发送到后端的数据
    let clockData = {
        openid: openid,
        userId: userId,
        id: new Date().getTime(), // 使用时间戳作为唯一 ID
        status: 1, // 打卡成功状态
        positionUuid: allPoints.map(point => point.uuid).join(','), // 所有打卡点的 UUID
        clockInTime: runStartTime, // 打卡开始时间
        clockOutTime: timer.getTodayTime(), // 打卡结束时间
        description: "打卡成功",
        distance: that.data.distance_data // 运动距离
    };

    // 使用封装的请求工具发送数据到后端接口
    apiService.wxRequestPromise({
        url: 'https://jkp.yxqz.top/wechat/clock/add', // 后端接口地址
        method: 'POST',
        data: clockData,
        header: {
            'content-type': 'application/json'
        }
    })
    .then(res => {
        console.log('打卡数据发送成功', res);
        wx.showToast({
            title: '打卡数据已上传',
            icon: 'success'
        });
    })
    .catch(err => {
        console.error('打卡数据发送失败', err);
        wx.showToast({
            title: '打卡数据上传失败',
            icon: 'none'
        });
    });

    // 清理缓存和状态
    that.initNumList();
    pointIndex = 1;
    allPointInfo4Finish = [];
    runStartTime = "";
    timer.end();
    timer.reset();
},

  //载入缓存数据
  initRun() {
    let sex = wx.getStorageSync('sex');
    let weight = wx.getStorageSync('weight');
    let height = wx.getStorageSync('height');
    if (sex) {
      //男性
      weight = 60;
      height = 172;
    } else {
      //女性
      weight = 52;
      height = 166;
    }
    lebu.setWeight(weight);
    lebu.setHeight(height);
    let that = this;
    if (this.data.runType == 0) {
      wx.getLocation({
        altitude: true,
        success(res) {

          that.setData({
            latitude: res.latitude,
            longitude: res.longitude,
            altitude: res.altitude,
          })

          setTimeout(function () {
            let obj = wx.createMapContext('myMap')
            obj.addGroundOverlay({
              id:1,
              src:'http://iptdata.natapp1.cc/statics/images/map23.png',
              bounds:{
                // 西南
                southwest:{
                  longitude:104.68199,
                  latitude:31.48791
                },
                // 东北
                northeast:{
     
                     longitude:104.690753,
                     latitude:31.494641
                }
              },
              zIndex:99,
              success:res=>{
                 console.log('initRun():'+res)
              }
            })

            obj.initMarkerCluster({
              enableDefaultStyle:true,
              zoomOnClick:true,
              gridSize:60,
              complete(res){
                console.log("initMarker",res)
              }
            })

            obj.moveToLocation();
          }, 1000);
        },
        fail() {
          that.checkLocation();
        }
      });
    }
  },
  startRun() {
    let that = this;
    this.vibrateFunc(1);
    //增加点击开始时间的记录，存放形式：全局字符；初始化：{退出打卡界面、跑完一圈、}
    var getCruTime = timer.getTodayTime();
    runStartTime = getCruTime;
    ifRunStart = true;
    this.setData({
      scale: 16
    })

    if (this.data.runType == 0) {
      wx.startLocationUpdateBackground({
        success: (res) => {
        },
        fail: (res) => {
          console.log('startRun():'+res)
        }
      });
    }
    wx.startAccelerometer({
      interval: 'normal',
      success() {
        timer.start();
        that.setData({
        motion_status: 1,
        });
      },
      fail(){
        timer.start();
        that.setData({
        motion_status: 1,
        });
      }
    })
    this.data.time_id = setInterval(function () {
      let time_data = timer.getTime();
      that.setData({
        time_data: time_data,
      });
    }, 500);
  },
  pauseRun() {
    this.vibrateFunc(1)
    let that = this;
    timer.end();
    if (this.data.runType == 0) {
      wx.stopLocationUpdate({
        complete: (res) => {

        },
      });
    }
    wx.stopAccelerometer({
      complete: (res) => {
        that.setData({
          motion_status: 2
        });
      },
    })
  },
  reRun() {
    this.vibrateFunc(1) 
    var that = this;
    that.setData({
      motion_status: 1,
    });
     timer.start();

    wx.startAccelerometer({
      interval: 'normal',
      success() {
      }
    })
    if (this.data.runType === 0) {
      wx.startLocationUpdate({
        success: (res) => {
        },
        fail: (res) => {
          console.log('reRun():'+res)
        }
      });
    }

    wx.onAccelerometerChange(res => {
    });

  },
  stopRun() {
    this.vibrateFunc(2)
    let that = this;
    timer.end();
    timer.reset();
    if (this.data.runType == 0) {
      wx.stopLocationUpdate({
        complete: (res) => {

        },
      });
    }
    wx.stopAccelerometer({
      complete: (res) => {
        that.setData({
          motion_status: 2
        });
      },
    });
    if (this.data.distance_data == 0) {
      wx.showModal({
        title: '未检测到任何移动',
        content: '继续运动还是舍弃这条记录?',
        cancelText: '舍弃',
        confirmText: '继续',
        success(res) {
          if (res.confirm) {
            that.reRun();
          } else {
            wx.switchTab({
              url: '../index/index',
            })
          }
        }
      })
    } else if (this.data.distance_data < 0.1) {
      wx.showModal({
        title: '移动距离太短',
        content: '继续运动还是舍弃这条记录?',
        cancelText: '舍弃',
        confirmText: '继续',
        success(res) {
          if (res.confirm) {
            that.reRun();
          } else {
            wx.switchTab({
              url: '../index/index',
            })
          }
        }
      });
    } else {
      lebu.reset();
      clearInterval(this.data.time_id);
      let id = parseInt(Date.now() / 1000)
      wx.setStorageSync('RunInfo-' + id, JSON.stringify({
          //记录跑步的总时长，格式为“时:分:秒
        time_data: this.data.time_data,
        //记录跑步的平均速度，格式为“分'秒''”（分钟和秒）
        speed_data: this.data.speed_data,
        //记录跑步过程中消耗的卡路里，单位为千卡。
        kcal_data: this.data.kcal_data,
        //记录跑步的总距离，单位为千米。
        distance_data: this.data.distance_data,
        //记录每公里的配速，格式为“分'秒''”。
        km_speed_data: this.data.km_speed_data,
        //记录跑步轨迹的坐标点数组，每个点包含经度和纬度。
        points_data: this.data.polyline[0].points,
        //记录跑步过程中的海拔数据数组，单位为米。
        altitude_data: this.data.altitude_data,
        //记录最后一个定位点的海拔高度，单位为米。
        altitude: this.data.altitude,
        //标记跑步的类型，例如普通跑步、训练模式等。
        runType: this.data.runType
      }));
      wx.redirectTo({
        url: './statement?id=' + id,
      })
    }
  },
  vibrateFunc(mode) {
    if (wx.getStorageSync('vibrate')) {
      if (mode == 1) {
        wx.vibrateShort({
          complete: (res) => {},
        })
      }

      if (mode == 2) {
        wx.vibrateLong({
          complete: (res) => {},
        })
      }
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.setScreenHeight();
  },
  //设定地图高度为全屏幕高度 
  setScreenHeight() {
    let that = this;
    wx.getSystemInfo({
      success: (res) => {
        that.setData({
          screenHeight: (res.screenHeight * 0.901) + "px"
        })
      },
    })
  },
  //检测是否开启后台定位,并引导用户开启
  checkLocation() {
    if (this.data.runType == 1) return;
    wx.getSetting({
      success(res) {
        let ulb = res.authSetting["scope.userLocationBackground"];

        //console.log(res.authSetting)
        if (ulb == false || ulb == undefined || res.authSetting["scope.userLocation"] == false) {
          wx.showModal({
            title: "提示",
            content: "请先设置位置信息为\"使用小程序期间和离开小程序后\",才可运行跑步模块",
            success(res) {
              if (res.confirm) {
                wx.openSetting({})
              } else {
                wx.switchTab({
                  url: '../index/index',
                })
              }
            }
          })
        }
      }
    })
  },
  checkDistance(lat2, lng2, cur_time) {
    let obj = this.data.polyline[0].points[this.data.polyline[0].points.length - 1];
    // console.log(this.data.polyline[0].points);
    let lat1 = obj.latitude;
    let lng1 = obj.longitude;
    // 调用 return的距离单位为m
    let radLat1 = lat1 * Math.PI / 180.0;
    let radLat2 = lat2 * Math.PI / 180.0;
    let a = radLat1 - radLat2;
    let b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
    let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
      Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137; // EARTH_RADIUS;
    s = Math.round(s * 10000) / 10; //m

    let time_differece = cur_time - this.data.points_time; //秒
    this.data.points_time = cur_time;
    if (time_differece <= 0) {
      return false;
    }

    let cal_distance = (lebu.getStride() / 100) * time_differece; //cm => m
    if ((s <= cal_distance && s > 0) || (s <= this.data.distance_data && this.data.distance > 0) || (s < 35 && s > 0)) {
      return true;
    } else {
      return false;
    }

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.checkLocation();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // wx.setNavigationBarTitle({
    //   title: '跑步记录',
    // })
    // wx.stopLocationUpdate({
    //   complete: (res) => {},
    // })
  },
  onUnload() {
   
    let that = this;
    this.closeBluetoothAdapter();
    //重置数组，每次退出
    allPointInfo4Finish = [];
    //时间计数器重置
    timer.end();
    timer.reset();
    //定位停止
    if (this.data.runType == 0) {
      wx.stopLocationUpdate({
        complete: (res) => {

        },
      });
    }
    //加速度传感器停止监测
    wx.stopAccelerometer({
      complete: (res) => {
        that.setData({
          motion_status: 2
        });
      },
    });
    //跑步模块重置
    lebu.reset();
  }
})

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}
function sleep(numberMillis) {
  console.log("睡眠" + numberMillis + "毫秒")
  var now = new Date();
  var exitTime = now.getTime() + numberMillis;
  while (true) {
      now = new Date();
      if (now.getTime() > exitTime)
          return;
  }
}